import BaseButton from '@/components/base/BaseButton';
import { useModal } from '@/components/base/BaseModal';
import { history } from '@/router';
import { getMessageCount, getMessages, readAllMessage, readMessage } from '@/services/global';
import useUserStore from '@/store/user';
import { useRequest } from '@/utils/request';
import useLoadMore from '@/utils/request/useLoadMore';
import {
  BellOutlined,
  BgColorsOutlined,
  LockOutlined,
  LogoutOutlined,
  MessageFilled,
  MessageOutlined,
  UserOutlined
} from '@ant-design/icons';
import {
  Avatar,
  Badge,
  Card,
  Divider,
  Dropdown,
  List,
  Menu,
  Skeleton,
  Space,
  Spin,
  Tooltip
} from 'antd';
import { FC, memo } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import styled from 'styled-components';
import ThemeModal from './modals/ThemeModal';
import UpdatePasswordModal from './modals/UpdatePasswordModal';

const TopHeader = styled.div`
  display: flex;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  color: #fff;
  border-bottom: 1px solid ${(props) => props.theme.borderColor};
  .logo {
    display: flex;
    align-items: center;
    height: 100%;
    font-size: 22px;
  }
`;
const HeaderActions = styled.div`
  display: flex;
  align-items: center;
  margin-left: auto;
  gap: 32px;
  svg {
    font-size: 16px;
    cursor: pointer;
  }
  .welcome-info {
    height: 48px;
    font-weight: 500;
    font-size: 16px;
    line-height: 48px;
    text-align: center;
    .ant-avatar {
      background-color: ${(props) => props.theme.primaryColor};
    }
  }
`;
const titles = ['故障', '维修', '保障'];
const Header: FC = () => {
  const userinfo = useUserStore((state) => state.userinfo);
  const themeModal = useModal(ThemeModal);
  const updatePasswordModal = useModal(UpdatePasswordModal);
  const { pathname } = history.location;
  const messageCount = useRequest(getMessageCount, {
    pollingInterval: 1000 * 60 * 5,
    pollingWhenHidden: true
  });
  const list = useLoadMore(getMessages, {
    isNoMore: (d) => (d ? d.list.length >= d.rowCount : false),
    manual: true
  });
  const read = useRequest(readMessage, {
    manual: true,
    fetchKey: (id) => id,
    onSuccess() {
      messageCount.run();
    }
  });
  const readAll = useRequest(readAllMessage, {
    manual: true,
    onSuccess() {
      list.reload();
      messageCount.run();
    }
  });
  return (
    <TopHeader>
      <div className='logo'>装备健康监控平台</div>
      <HeaderActions>
        <Dropdown
          onVisibleChange={(visible) => {
            if (visible) {
              list.reload();
            }
          }}
          trigger={['click']}
          placement='bottomRight'
          overlay={
            <div>
              <Card
                bodyStyle={{ padding: 0 }}
                actions={[
                  <BaseButton
                    disabled={readAll.loading || messageCount.data?.unreadCount === 0}
                    type='text'
                    onClick={() => {
                      readAll.run();
                    }}
                    loading={readAll.loading}
                  >
                    全部已读
                  </BaseButton>
                ]}
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}
              >
                <div
                  id='scrollableDiv'
                  style={{
                    height: 400,
                    width: 300,
                    background: '#fff',
                    overflow: 'auto',
                    padding: '0 16px'
                  }}
                >
                  <InfiniteScroll
                    dataLength={list.data?.list.length || 0}
                    next={list.loadMore}
                    hasMore={!list.noMore}
                    loader={list.loadingMore ? <Skeleton paragraph={{ rows: 1 }} active /> : null}
                    endMessage={
                      (list.data?.list.length || 0) > 0 && <Divider plain>没有更多了！</Divider>
                    }
                    scrollableTarget='scrollableDiv'
                  >
                    {list.data?.list && (
                      <List
                        loading={list.loading}
                        dataSource={list.data.list}
                        renderItem={(item, index) => {
                          return (
                            <Spin spinning={read.fetches[item.id]?.loading === true}>
                              <List.Item
                                key={item.id}
                                onClick={async () => {
                                  if (item.status === 0 && !read.fetches[item.id]?.loading) {
                                    const bool = await read.run(item.id);
                                    if (bool) {
                                      list.data!.list[index].status = 1;
                                    }
                                  }
                                }}
                              >
                                <List.Item.Meta
                                  avatar={
                                    item.status === 0 ? (
                                      <MessageFilled />
                                    ) : (
                                      <MessageOutlined style={{ color: 'rgba(0, 0, 0, 0.45)' }} />
                                    )
                                  }
                                  title={
                                    <div
                                      style={{
                                        color: item.status === 0 ? '#000' : 'rgba(0, 0, 0, 0.45)'
                                      }}
                                    >
                                      {titles[item.type]}
                                    </div>
                                  }
                                  description={
                                    <div
                                      style={{
                                        color: item.status === 0 ? '#000' : 'rgba(0, 0, 0, 0.45)'
                                      }}
                                    >
                                      {item.content}
                                    </div>
                                  }
                                />
                              </List.Item>
                            </Spin>
                          );
                        }}
                      />
                    )}
                  </InfiniteScroll>
                </div>
              </Card>
            </div>
          }
        >
          <div>
            <Badge count={messageCount.data?.unreadCount} offset={[5, -4]}>
              <BellOutlined style={{ color: '#fff' }} />
            </Badge>
          </div>
        </Dropdown>
        <div>
          <Tooltip placement='bottom' title='修改密码'>
            <LockOutlined onClick={() => updatePasswordModal.load({})} />
          </Tooltip>
        </div>
        <div>
          <Tooltip placement='bottom' title='修改主题'>
            <BgColorsOutlined onClick={() => themeModal.load({})} />
          </Tooltip>
        </div>
        <Dropdown
          overlay={
            <Menu>
              <Menu.Item
                onClick={() => {
                  history.push('/profile');
                }}
                icon={<UserOutlined />}
              >
                个人中心
              </Menu.Item>
              <Menu.Item
                onClick={() => history.replace(`/logout?redirect=${pathname}`)}
                icon={<LogoutOutlined />}
              >
                退出系统
              </Menu.Item>
            </Menu>
          }
        >
          <div className='welcome-info'>
            <Space>
              <Avatar>{(userinfo.realName ?? '').substr(0, 1)}</Avatar>
              您好！ {userinfo.realName}
            </Space>
          </div>
        </Dropdown>
      </HeaderActions>
    </TopHeader>
  );
};

export default memo(Header);
